<?php

namespace app\xiaohongshu\controller;

use app\common\controller\XiaohongshuApi;
use app\common\library\Upload;
use think\Config;
use think\Exception;

class Common extends XiaohongshuApi
{
    
    protected $noNeedLogin = ['upload'];
    
    /**
     * 上传文件
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        
        $file = $this->request->file('file');
        if (empty($file)) {
            return $this->error('请选择要上传的文件');
        }

        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
            
            if ($attachment) {
                return $this->success('上传成功', [
                    'url' => cdnurl($attachment->url, true),
                    'path' => $attachment->url,
                    'size' => $attachment->filesize,
                    'mime_type' => $attachment->mimetype,
                    'name' => $attachment->filename
                ]);
            } else {
                return $this->error($upload->getError());
            }
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}
